<template>
  <div class="app-container">
    <el-row>
      <!--用户数据-->
      <el-col :span="24" :xs="24">
        <el-form :inline="true" v-show="showSearch" label-width="140px" :label-position="isPhone ? 'top' : 'left'">
          <el-form-item label="姓名" prop="nickName">
            <el-input
              v-model="queryParams.nickName"
              placeholder="请输入姓名"
              clearable
              style="width: 180px"
            />
          </el-form-item>
          <el-form-item label="学校" prop="trainUniversity">
            <el-select
              v-model="queryParams.trainUniversity"
              placeholder="请选择学校"
              clearable
              style="width: 180px"
            >
              <el-option
                v-for="item in university"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="专业" prop="trainMajor">
            <el-input
              v-model="queryParams.trainMajor"
              placeholder="请输入专业"
              clearable
              style="width: 180px"
            />
          </el-form-item>
          <el-form-item label="入企实践开始时间" prop="practiceStartYear">
            <el-select
              v-model="queryParams.practiceStartYear"
              placeholder="请选择年份"
              clearable
              style="width: 180px"
            >
              <el-option
                v-for="year in yearOptions"
                :key="year"
                :label="year + '年'"
                :value="year"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery"
              >搜索</el-button
            >
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="Plus"
              @click="handleAdd"
              v-hasRole="['admin', 'student']"
              >新增</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="warning"
              plain
              icon="Download"
              @click="handleExport"
              v-hasPermi="['system:user:export']"
              >导出</el-button
            >
          </el-col>
          <right-toolbar
            v-model:showSearch="showSearch"
            @queryTable="handleGetList"
            :columns="columns"
          ></right-toolbar>
        </el-row>

        <el-table
          v-loading="loading"
          :data="list"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column
            label="姓名"
            align="center"
            key="nickName"
            prop="nickName"
            v-if="columns[1].visible"
            :show-overflow-tooltip="true"
            width="100"
          />
          <el-table-column
            label="学校"
            align="center"
            key="trainUniversity"
            prop="trainUniversity"
            v-if="columns[2].visible"
            :show-overflow-tooltip="true"
            width="150"
          >
            <template #default="scope">
              {{ getUniversityText(scope.row.trainUniversity) }}
            </template>
          </el-table-column>
          <el-table-column
            label="专业"
            align="center"
            key="trainMajor"
            prop="trainMajor"
            v-if="columns[3].visible"
            :show-overflow-tooltip="true"
            width="150"
          />
          <el-table-column
            label="培养单位"
            align="center"
            key="trainUnit"
            prop="trainUnit"
            v-if="columns[4].visible"
            :show-overflow-tooltip="true"
            width="150"
          />
          <el-table-column
            label="入企时间"
            align="center"
            key="aa1"
            prop="aa1"
            v-if="columns[5].visible"
            :show-overflow-tooltip="true"
            width="150"
          />
          <el-table-column
            label="课题名称"
            align="center"
            key="joinEntTopicName"
            prop="joinEntTopicName"
            v-if="columns[6].visible"
            :show-overflow-tooltip="true"
            width="200"
          />
          <el-table-column
            label="课题简介"
            align="center"
            key="joinEntTopicIntroduction"
            prop="joinEntTopicIntroduction"
            v-if="columns[7].visible"
            :show-overflow-tooltip="true"
            width="250"
          />
          <el-table-column
            label="论文开题计划时间"
            align="center"
            key="thesisStartTime"
            prop="thesisStartTime"
            v-if="columns[8].visible"
            width="140"
          />
          <el-table-column
            label="中期考核计划时间"
            align="center"
            key="thesisMidTime"
            prop="thesisMidTime"
            v-if="columns[9].visible"
            width="140"
          />
          <el-table-column
            label="论文预答辩计划时间"
            align="center"
            key="thesisPreTime"
            prop="thesisPreTime"
            v-if="columns[10].visible"
            width="140"
          />
          <el-table-column
            label="论文答辩计划时间"
            align="center"
            key="thesisEndTime"
            prop="thesisEndTime"
            v-if="columns[11].visible"
            width="140"
          />
          <el-table-column
            label="操作"
            align="center"
            width="150"
            fixed="right"
            class-name="small-padding fixed-width"
          >
            <template #default="scope">
              <el-tooltip content="详情" placement="top">
                <el-button
                  link
                  type="info"
                  icon="View"
                  @click="handleDetail(scope.row)"
                ></el-button>
              </el-tooltip>
              <el-tooltip content="修改" placement="top">
                <el-button
                  link
                  type="primary"
                  icon="Edit"
                  @click="handleUpdate(scope.row)"
                  v-hasRole="['admin', 'student']"
                ></el-button>
              </el-tooltip>
              <el-tooltip content="删除" placement="top">
                <el-button
                  link
                  type="primary"
                  icon="Delete"
                  @click="handleDelete(scope.row)"
                  v-hasRole="['admin', 'student']"
                ></el-button>
              </el-tooltip>
              <el-tooltip
                content="提交"
                placement="top"
                v-if="
                  scope.row.approvalStatus === 'no_submit' ||
                  scope.row.approvalStatus === 'rejected'
                "
              >
                <el-button
                  link
                  type="warning"
                  icon="Upload"
                  @click="handleSubmit(scope.row)"
                  v-hasRole="['admin', 'student']"
                ></el-button>
              </el-tooltip>
              <el-tooltip
                content="审批"
                placement="top"
                v-if="scope.row.approvalAuth"
              >
                <el-button
                  link
                  type="success"
                  icon="Check"
                  @click="handleApprove(scope.row)"
                ></el-button>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
        <pagination
          v-show="total > 0"
          :total="total"
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          @pagination="handleGetList"
        />
      </el-col>
    </el-row>

    <!-- 添加或修改用户配置对话框 -->
    <el-dialog
      :title="title"
      v-model="open"
      width="1200px"
      append-to-body
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <el-form :model="form" :rules="rules" ref="formRef" label-width="150px" :label-position="isPhone ? 'top' : 'left'">
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="学生" prop="userId" label-width="50px">
              <el-select
                v-model="form.userId"
                placeholder="请选择学生"
                clearable
                :disabled="title === '查看企业实践计划详情' || true"
              >
                <el-option
                  v-for="item in userList"
                  :key="item.userId"
                  :label="item.nickName"
                  :value="item.userId"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <template v-if="formUserInfo">
            <el-col :span="12">
              <el-form-item label="学校" label-width="50px">
                <el-input
                  :value="getUniversityText(formUserInfo.trainUniversity)"
                  disabled
                >
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="专业" label-width="50px">
                <el-input v-model="formUserInfo.trainMajor" disabled>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="培养单位" label-width="80px">
                <el-input v-model="formUserInfo.trainDeptName" disabled>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="课题名称" label-width="80px">
                <el-input v-model="formUserInfo.joinEntTopicName" disabled>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="课题简介" label-width="80px">
                <el-input
                  v-model="formUserInfo.joinEntTopicIntroduction"
                  disabled
                >
                </el-input>
              </el-form-item>
            </el-col>
          </template>
          <el-col :span="12">
            <el-form-item label="论文开题计划时间" prop="thesisStartTime">
              <el-date-picker
                v-model="form.thesisStartTime"
                type="date"
                placeholder="请选择论文开题计划时间"
                value-format="YYYY-MM-DD"
                style="width: 100%"
                :disabled="title === '查看企业实践计划详情'"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="中期考核计划时间" prop="thesisMidTime">
              <el-date-picker
                v-model="form.thesisMidTime"
                type="date"
                placeholder="请选择中期考核计划时间"
                value-format="YYYY-MM-DD"
                style="width: 100%"
                :disabled="title === '查看企业实践计划详情'"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="论文预答辩计划时间" prop="thesisPreTime">
              <el-date-picker
                v-model="form.thesisPreTime"
                type="date"
                placeholder="请选择论文预答辩计划时间"
                value-format="YYYY-MM-DD"
                style="width: 100%"
                :disabled="title === '查看企业实践计划详情'"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="论文答辩计划时间" prop="thesisEndTime">
              <el-date-picker
                v-model="form.thesisEndTime"
                type="date"
                placeholder="请选择论文答辩计划时间"
                value-format="YYYY-MM-DD"
                style="width: 100%"
                :disabled="title === '查看企业实践计划详情'"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="计划" label-width="50px">
              <div class="plan-table-container">
                <el-table :data="form.planDetails" border style="width: 100%">
                  <el-table-column label="计划名称" width="150" prop="planName" />
                  <el-table-column label="计划月份" width="150">
                    <template #default="scope">
                      {{ scope.row.planMonth ? formatMonth(scope.row.planMonth) : '-' }}
                    </template>
                  </el-table-column>
                  <el-table-column label="开始时间" width="150" prop="planStartTime" />
                  <el-table-column label="结束时间" width="150" prop="planEndTime" />
                  <el-table-column label="实践目标" min-width="200">
                    <template #default="scope">
                      <div class="text-overflow" :title="scope.row.planTarget">
                        {{ scope.row.planTarget || '-' }}
                      </div>
                    </template>
                  </el-table-column>
                  <el-table-column label="操作" width="140" fixed="right">
                    <template #default="scope">
                      <el-button
                        type="primary"
                        size="small"
                        @click="handleEditPlan(scope.row, scope.$index)"
                        v-if="title !== '查看企业实践计划详情'"
                      >
                        编辑
                      </el-button>
                      <el-button
                        type="danger"
                        size="small"
                        @click="removePlan(scope.$index)"
                        v-if="form.approvalStatus !== 'approved' && title !== '查看企业实践计划详情'"
                      >
                        删除
                      </el-button>
                    </template>
                  </el-table-column>
                </el-table>
                <div style="margin-top: 10px">
                  <el-button
                    v-if="(!form.planDetails || form.planDetails?.length < 50) && title !== '查看企业实践计划详情'"
                    type="primary"
                    @click="handleAddPlan"
                    size="small"
                  >
                    添加计划
                  </el-button>
                </div>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <el-form-item
        label="审核意见"
        prop="approvalRemark"
        style="margin-bottom: 0"
        v-if="form.approvalStatus === 'rejected'"
      >
        <el-input
          v-model="form.approvalRemark"
          disabled
          type="textarea"
          placeholder="请输入审核意见"
          :rows="3"
          style="width: 100%"
        ></el-input>
      </el-form-item>
      <template #footer>
        <div class="dialog-footer">
          <!-- 审批模式下的审核意见字段 -->
          <div v-if="title === '审批企业实践计划'" style="margin-bottom: 20px">
            <el-form-item
              label="审核意见"
              prop="approvalRemark"
              style="margin-bottom: 0"
            >
              <el-input
                v-model="form.approvalRemark"
                type="textarea"
                placeholder="请输入审核意见"
                :rows="3"
                style="width: 100%"
              ></el-input>
            </el-form-item>
          </div>

          <!-- 普通编辑模式按钮 -->
          <template v-if="title !== '审批企业实践计划' && title !== '查看企业实践计划详情'">
            <el-button 
              type="primary" 
              @click="submitForm"
              :loading="submitLoading"
              :disabled="submitLoading"
            >确 定</el-button>
            <el-button @click="cancel">取 消</el-button>
          </template>

          <!-- 详情模式按钮 -->
          <template v-else-if="title === '查看企业实践计划详情'">
            <el-button @click="cancel">关 闭</el-button>
          </template>

          <!-- 审批模式按钮 -->
          <template v-else>
            <el-button 
              type="success" 
              @click="handleApprovePass"
              :loading="approvePassLoading"
              :disabled="approvePassLoading"
              >通 过</el-button
            >
            <el-button 
              type="danger" 
              @click="handleApproveReject"
              :loading="approveRejectLoading"
              :disabled="approveRejectLoading"
              >驳 回</el-button
            >
            <el-button @click="cancel">取 消</el-button>
          </template>
        </div>
      </template>
    </el-dialog>

    <!-- 计划编辑对话框 -->
    <el-dialog
      :title="planDialogTitle"
      v-model="planDialogVisible"
      width="600px"
      append-to-body
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <el-form :model="planForm" :rules="planRules" ref="planFormRef" label-width="100px" :label-position="isPhone ? 'top' : 'left'">
        <el-form-item label="计划名称" prop="planName">
          <el-input
            v-model="planForm.planName"
            placeholder="请输入计划名称"
          />
        </el-form-item>
        <el-form-item label="计划月份" prop="planMonth">
          <el-date-picker
            v-model="planForm.planMonth"
            type="month"
            placeholder="请选择计划月份"
            style="width: 100%"
            @change="onPlanMonthChange"
          />
        </el-form-item>
        <el-form-item label="开始时间" prop="planStartTime">
          <el-date-picker
            v-model="planForm.planStartTime"
            type="date"
            placeholder="请选择开始时间"
            value-format="YYYY-MM-DD"
            style="width: 100%"
            @change="onStartTimeChange"
          />
        </el-form-item>
        <el-form-item label="结束时间" prop="planEndTime">
          <el-date-picker
            v-model="planForm.planEndTime"
            type="date"
            placeholder="请选择结束时间"
            value-format="YYYY-MM-DD"
            style="width: 100%"
            @change="validatePlanDateRange"
          />
        </el-form-item>
        <el-form-item label="实践目标" prop="planTarget">
          <el-input
            v-model="planForm.planTarget"
            type="textarea"
            :rows="4"
            placeholder="请输入实践目标"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button 
            type="primary" 
            @click="submitPlanForm"
            :loading="planSubmitLoading"
            :disabled="planSubmitLoading"
          >确 定</el-button>
          <el-button @click="cancelPlanForm">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="EnterprisePracticeProgram">
import {
  getList,
  addItem,
  editItem,
  delItem,
  getDetail,
} from "@/api/enterprise-practice-program";
import { submitApproval, handleApproval } from "@/api/approval";
import { getStudentList } from "@/api/common";
import useUserStore from "@/store/modules/user";
import { isPhone } from "@/utils/index";
import { yearOptions } from "@/utils/constant";

const router = useRouter();
const { proxy } = getCurrentInstance();
const { sys_yes_no, university } = proxy.useDict("sys_yes_no", "university");

const list = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

// 列显隐信息
const columns = ref([
  { key: 0, label: `编号`, visible: true },
  { key: 1, label: `姓名`, visible: true },
  { key: 2, label: `学校`, visible: true },
  { key: 3, label: `专业`, visible: true },
  { key: 4, label: `培养单位`, visible: true },
  { key: 5, label: `入企时间`, visible: true },
  { key: 6, label: `课题名称`, visible: true },
  { key: 7, label: `课题简介`, visible: true },
  { key: 8, label: `论文开题计划时间`, visible: true },
  { key: 9, label: `中期考核计划时间`, visible: true },
  { key: 10, label: `论文预答辩计划时间`, visible: true },
  { key: 11, label: `论文答辩计划时间`, visible: true },
]);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    nickName: undefined,
    trainUniversity: undefined,
    trainMajor: undefined,
    practiceStartYear: undefined,
  },
  rules: {
    userId: [{ required: true, message: "请选择学生", trigger: "change" }],
    thesisStartTime: [
      { required: true, message: "请选择论文开题计划时间", trigger: "change" },
    ],
    thesisMidTime: [
      { required: true, message: "请选择中期考核计划时间", trigger: "change" },
    ],
    thesisPreTime: [
      {
        required: true,
        message: "请选择论文预答辩计划时间",
        trigger: "change",
      },
    ],
    thesisEndTime: [
      { required: true, message: "请选择论文答辩计划时间", trigger: "change" },
    ],
  },
});

const { queryParams, form, rules } = toRefs(data);

const userList = ref([]);

// 按钮loading状态
const submitLoading = ref(false);
const approvePassLoading = ref(false);
const approveRejectLoading = ref(false);
const planSubmitLoading = ref(false);

// 计划编辑对话框相关数据
const planDialogVisible = ref(false);
const planDialogTitle = ref("");
const planEditIndex = ref(-1); // 编辑的计划索引，-1表示新增
const planForm = ref({
  planName: "",
  planMonth: "",
  planStartTime: "",
  planEndTime: "",
  planTarget: "",
});

// 计划表单验证规则
const planRules = {
  planName: [
    { required: true, message: "请输入计划名称", trigger: "blur" }
  ],
  planMonth: [
    { required: true, message: "请选择计划月份", trigger: "change" }
  ],
  planStartTime: [
    { required: true, message: "请选择开始时间", trigger: "change" }
  ],
  planEndTime: [
    { required: true, message: "请选择结束时间", trigger: "change" }
  ],
  planTarget: [
    { required: true, message: "请输入实践目标", trigger: "blur" }
  ],
};

const formUserInfo = computed(() =>
  userList.value.find((t) => t.userId === form.value.userId)
);

/** 查询用户列表 */
function handleGetList() {
  loading.value = true;
  getList(queryParams.value).then((res) => {
    loading.value = false;
    list.value = res.rows;
    total.value = res.total;
  });
}
/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  handleGetList();
}
function resetQuery() {
  queryParams.value.nickName = undefined;
  queryParams.value.trainUniversity = undefined;
  queryParams.value.trainMajor = undefined;
  queryParams.value.practiceStartYear = undefined;
  handleQuery();
}
/** 删除按钮操作 */
function handleDelete(row) {
  const id = row.id || ids.value;
  proxy.$modal
    .confirm('是否确认删除编号为"' + id + '"的数据项？')
    .then(function () {
      return delItem(id);
    })
    .then(() => {
      handleGetList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}
/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    "system/user/export",
    {
      ...queryParams.value,
    },
    `user_${new Date().getTime()}.xlsx`
  );
}

/** 选择条数  */
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 重置操作表单 */
function reset() {
  form.value = {
    userId: useUserStore().id,
    thesisStartTime: "",
    thesisMidTime: "",
    thesisPreTime: "",
    thesisEndTime: "",
    planDetails: [
    ],
  };
  proxy.resetForm("formRef");
}
/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}
/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加企业实践计划";
}
/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const id = row.id || ids.value;
  getDetail(id).then((response) => {
    form.value = response.data;
    // 如果没有计划详情，初始化一个空的计划
    if (!form.value.planDetails) {
      form.value.planDetails = [
      ];
    }
    open.value = true;
    title.value = "修改企业实践计划";
  });
}
/** 提交按钮 */
function submitForm() {
  // 防止重复提交
  if (submitLoading.value) return;
  
  proxy.$refs["formRef"].validate((valid) => {
    if (valid) {
      // 校验计划详情
      const planValidationResult = validatePlanDetails();
      if (!planValidationResult.valid) {
        proxy.$modal.msgError(planValidationResult.message);
        return;
      }

      submitLoading.value = true;
      const submitData = {
        ...form.value,
      };

      if (form.value.id != undefined) {
        editItem(submitData).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          handleGetList();
        }).catch((error) => {
          console.error("修改失败:", error);
        }).finally(() => {
          submitLoading.value = false;
        });
      } else {
        addItem(submitData).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          handleGetList();
        }).catch((error) => {
          console.error("新增失败:", error);
        }).finally(() => {
          submitLoading.value = false;
        });
      }
    }
  });
}

// 提交审核
function handleSubmit(row) {
  const id = row.id || ids.value;
  const item = list.value.find(item => item.id === id);
  proxy.$modal
    .confirm("是否确认提交审核？")
    .then(function () {
      return submitApproval({
        businessId: id,
        approvalTypeCode: "ent_plan_flow",
        approvalInfo: JSON.stringify(item)
      });
    })
    .then(() => {
      handleGetList();
      proxy.$modal.msgSuccess("提交成功");
    })
    .catch(() => {});
}

// 审批操作
function handleApprove(row) {
  reset();
  const id = row.id || ids.value;
  getDetail(id).then((response) => {
    form.value = {
      ...response.data,
      approvalRemark: "",
    };
    open.value = true;
    title.value = "审批企业实践计划";
  });
}

// 通过审批
function handleApprovePass() {
  // 防止重复提交
  if (approvePassLoading.value) return;
  
  approvePassLoading.value = true;
  const approvalData = {
    approvalInfoId: form.value.approvalInfoId,
    approvalNodeId: form.value.approvalNodeId,
    approvalStatus: "approved",
    remark: form.value.approvalRemark,
  };

  handleApproval(approvalData).then(() => {
    proxy.$modal.msgSuccess("审批通过");
    open.value = false;
    handleGetList();
  }).catch((error) => {
    console.error("审批通过失败:", error);
  }).finally(() => {
    approvePassLoading.value = false;
  });
}

// 驳回审批
function handleApproveReject() {
  if (!form.value.approvalRemark) {
    proxy.$modal.msgError("请填写审核意见");
    return;
  }

  // 防止重复提交
  if (approveRejectLoading.value) return;
  
  approveRejectLoading.value = true;
  const approvalData = {
    approvalInfoId: form.value.approvalInfoId,
    approvalNodeId: form.value.approvalNodeId,
    approvalStatus: "rejected",
    remark: form.value.approvalRemark,
  };

  handleApproval(approvalData).then(() => {
    proxy.$modal.msgSuccess("已驳回");
    open.value = false;
    handleGetList();
  }).catch((error) => {
    console.error("审批驳回失败:", error);
  }).finally(() => {
    approveRejectLoading.value = false;
  });
}

// 高校名称文本显示函数
const getUniversityText = (universityValue) => {
  if (!universityValue) return "未知";
  const dict = university.value?.find((item) => item.value === universityValue);
  return dict ? dict.label : universityValue;
};

// 添加计划
function handleAddPlan() {
  resetPlanForm();
  planEditIndex.value = -1;
  planDialogTitle.value = "添加计划";
  planDialogVisible.value = true;
}

// 编辑计划
function handleEditPlan(row, index) {
  resetPlanForm();
  planEditIndex.value = index;
  planDialogTitle.value = "编辑计划";
  
  // 填充表单数据
  planForm.value = {
    planName: row.planName || "",
    planMonth: row.planMonth || "",
    planStartTime: row.planStartTime || "",
    planEndTime: row.planEndTime || "",
    planTarget: row.planTarget || "",
  };
  
  planDialogVisible.value = true;
}

// 重置计划表单
function resetPlanForm() {
  planForm.value = {
    planName: "",
    planMonth: "",
    planStartTime: "",
    planEndTime: "",
    planTarget: "",
  };
  if (proxy.$refs.planFormRef) {
    proxy.$refs.planFormRef.resetFields();
  }
}

// 取消计划编辑
function cancelPlanForm() {
  planDialogVisible.value = false;
  resetPlanForm();
}

// 提交计划表单
function submitPlanForm() {
  // 防止重复提交
  if (planSubmitLoading.value) return;
  
  proxy.$refs.planFormRef.validate((valid) => {
    if (valid) {
      // 验证日期范围
      const dateValidation = validateSinglePlanDateRange(planForm.value);
      if (!dateValidation.valid) {
        proxy.$modal.msgError(dateValidation.message);
        return;
      }

      planSubmitLoading.value = true;
      
      if (!form.value.planDetails) {
        form.value.planDetails = [];
      }

      if (planEditIndex.value === -1) {
        // 新增计划
        form.value.planDetails.push({ ...planForm.value });
        proxy.$modal.msgSuccess("添加计划成功");
      } else {
        // 编辑计划
        form.value.planDetails[planEditIndex.value] = { ...planForm.value };
        proxy.$modal.msgSuccess("编辑计划成功");
      }

      planDialogVisible.value = false;
      resetPlanForm();
      planSubmitLoading.value = false;
    }
  });
}

// 验证单个计划的日期范围
function validateSinglePlanDateRange(plan) {
  if (!plan.planStartTime || !plan.planEndTime) {
    return { valid: true, message: "" };
  }

  const startDate = new Date(plan.planStartTime);
  const endDate = new Date(plan.planEndTime);

  // 验证开始时间和结束时间是否在计划月份内
  if (plan.planMonth) {
    const planMonthDate = new Date(plan.planMonth);
    const year = planMonthDate.getFullYear();
    const month = planMonthDate.getMonth();
    
    // 获取当月的第一天和最后一天
    const firstDay = new Date(year, month, 1);
    const lastDay = new Date(year, month + 1, 0);
    
    // 检查开始时间是否在计划月份内
    if (startDate < firstDay || startDate > lastDay) {
      return {
        valid: false,
        message: "开始时间必须在计划月份内"
      };
    }
    
    // 检查结束时间是否在计划月份内
    // if (endDate < firstDay || endDate > lastDay) {
    //   return {
    //     valid: false,
    //     message: "结束时间必须在计划月份内"
    //   };
    // }
  } else {
    // 如果没有选择计划月份，检查开始时间和结束时间是否在同一个月
    // const startYear = startDate.getFullYear();
    // const startMonth = startDate.getMonth();
    // const endYear = endDate.getFullYear();
    // const endMonth = endDate.getMonth();
    
    // if (startYear !== endYear || startMonth !== endMonth) {
    //   return {
    //     valid: false,
    //     message: "开始时间和结束时间必须在同一个月内"
    //   };
    // }
  }

  // 结束时间不能早于开始时间
  if (endDate < startDate) {
    return {
      valid: false,
      message: "结束时间不能早于开始时间"
    };
  }

  return { valid: true, message: "" };
}

// 实时验证计划日期范围
function validatePlanDateRange() {
  if (!planForm.value.planStartTime || !planForm.value.planEndTime) {
    return;
  }

  const validation = validateSinglePlanDateRange(planForm.value);
  if (!validation.valid) {
    proxy.$modal.msgWarning(validation.message);
  }
}

// 计划月份改变时的处理
function onPlanMonthChange() {
  // 清空已选择的开始时间和结束时间，因为它们可能不在新的月份范围内
  if (planForm.value.planStartTime || planForm.value.planEndTime) {
    planForm.value.planStartTime = "";
    planForm.value.planEndTime = "";
    proxy.$modal.msgInfo("计划月份已更改，请重新选择开始时间和结束时间");
  }
}

// 开始时间改变时的处理
function onStartTimeChange(value) {
  // if (value) {
  //   // 如果没有选择计划月份，自动设置为开始时间对应的月份
  //   if (!planForm.value.planMonth) {
  //     const startDate = new Date(value);
  //     const monthDate = new Date(startDate.getFullYear(), startDate.getMonth(), 1);
  //     planForm.value.planMonth = monthDate;
  //     proxy.$modal.msgSuccess("已自动设置计划月份为开始时间对应的月份");
  //   }
  // }
  
  // 执行日期范围验证
  validatePlanDateRange();
}

// 获取默认的开始时间日期（用于日期选择器的默认定位）
function getDefaultStartDate() {
  if (planForm.value.planMonth) {
    // 如果已选择计划月份，默认定位到该月份的第一天
    const planMonthDate = new Date(planForm.value.planMonth);
    return new Date(planMonthDate.getFullYear(), planMonthDate.getMonth(), 1);
  }
  // 如果没有选择计划月份，默认定位到当前月份的第一天
  const now = new Date();
  return new Date(now.getFullYear(), now.getMonth(), 1);
}

// 格式化月份显示
function formatMonth(monthValue) {
  if (!monthValue) return '';
  const date = new Date(monthValue);
  return `${date.getFullYear()}年${String(date.getMonth() + 1).padStart(2, '0')}月`;
}

// 详情操作
function handleDetail(row) {
  reset();
  const id = row.id || ids.value;
  getDetail(id).then((response) => {
    form.value = response.data;
    // 如果没有计划详情，初始化一个空的计划
    if (!form.value.planDetails) {
      form.value.planDetails = [];
    }
    open.value = true;
    title.value = "查看企业实践计划详情";
  });
}

// 禁用开始时间日期的函数
function disabledStartDate(time) {
  if (!planForm.value.planMonth) {
    // 如果没有选择计划月份，允许选择任何日期
    // 但可以限制为合理的日期范围，比如过去一年到未来一年
    const now = new Date();
    const oneYearAgo = new Date(now.getFullYear() - 1, now.getMonth(), now.getDate());
    const oneYearLater = new Date(now.getFullYear() + 1, now.getMonth(), now.getDate());
    return time < oneYearAgo || time > oneYearLater;
  }
  
  const planMonthDate = new Date(planForm.value.planMonth);
  const year = planMonthDate.getFullYear();
  const month = planMonthDate.getMonth();
  
  // 获取当月的第一天和最后一天
  const firstDay = new Date(year, month, 1);
  const lastDay = new Date(year, month + 1, 0);
  
  // 只允许选择计划月份内的日期
  return time < firstDay || time > lastDay;
}

// 禁用结束时间日期的函数
function disabledEndDate(time) {
  if (!planForm.value.planMonth) {
    // 如果没有选择计划月份，只限制不能早于开始时间
    if (planForm.value.planStartTime) {
      const startDate = new Date(planForm.value.planStartTime);
      return time < startDate;
    }
    // 如果没有开始时间，限制为合理的日期范围
    const now = new Date();
    const oneYearAgo = new Date(now.getFullYear() - 1, now.getMonth(), now.getDate());
    const oneYearLater = new Date(now.getFullYear() + 1, now.getMonth(), now.getDate());
    return time < oneYearAgo || time > oneYearLater;
  }
  
  const planMonthDate = new Date(planForm.value.planMonth);
  const year = planMonthDate.getFullYear();
  const month = planMonthDate.getMonth();
  
  // 获取当月的第一天和最后一天
  const firstDay = new Date(year, month, 1);
  const lastDay = new Date(year, month + 1, 0);
  
  // 只允许选择计划月份内的日期，并且不能早于开始时间
  if (time < firstDay || time > lastDay) {
    return true;
  }
  
  // 如果有开始时间，结束时间不能早于开始时间
  if (planForm.value.planStartTime) {
    const startDate = new Date(planForm.value.planStartTime);
    return time < startDate;
  }
  
  return false;
}

function addPlan() {
  handleAddPlan();
}

function removePlan(index) {
  if (form.value.planDetails && form.value.planDetails.length > 1) {
    form.value.planDetails.splice(index, 1);
  }
}

// 校验计划详情
function validatePlanDetails() {
  if (!form.value.planDetails || form.value.planDetails.length === 0) {
    return {
      valid: false,
      message: "至少需要添加一个计划"
    };
  }

  for (let i = 0; i < form.value.planDetails.length; i++) {
    const plan = form.value.planDetails[i];
    const rowIndex = i + 1;

    // 校验必填字段
    if (!plan.planName || !plan.planName.trim()) {
      return {
        valid: false,
        message: `第${rowIndex}行：计划名称不能为空`
      };
    }

    if (!plan.planMonth) {
      return {
        valid: false,
        message: `第${rowIndex}行：计划月份不能为空`
      };
    }

    if (!plan.planStartTime) {
      return {
        valid: false,
        message: `第${rowIndex}行：开始时间不能为空`
      };
    }

    if (!plan.planEndTime) {
      return {
        valid: false,
        message: `第${rowIndex}行：结束时间不能为空`
      };
    }

    if (!plan.planTarget || !plan.planTarget.trim()) {
      return {
        valid: false,
        message: `第${rowIndex}行：实践目标不能为空`
      };
    }

    // 校验时间逻辑
    const startDate = new Date(plan.planStartTime);
    const endDate = new Date(plan.planEndTime);

    // 结束时间不能早于开始时间
    if (endDate < startDate) {
      return {
        valid: false,
        message: `第${rowIndex}行：结束时间不能早于开始时间`
      };
    }

    // 计算时间差，不超过1个月（30天）
    const timeDiff = endDate.getTime() - startDate.getTime();
    const daysDiff = Math.ceil(timeDiff / (1000 * 60 * 60 * 24));

    if (daysDiff > 30) {
      return {
        valid: false,
        message: `第${rowIndex}行：时间跨度不能超过1个月（30天），当前为${daysDiff}天`
      };
    }
  }

  return {
    valid: true,
    message: ""
  };
}

// 实时校验日期范围
function validateDateRange(row, index) {
  if (!row.planStartTime || !row.planEndTime) {
    return;
  }

  const startDate = new Date(row.planStartTime);
  const endDate = new Date(row.planEndTime);
  const rowIndex = index + 1;

  // 结束时间不能早于开始时间
  if (endDate < startDate) {
    proxy.$modal.msgWarning(`第${rowIndex}行：结束时间不能早于开始时间`);
    return;
  }

  // 计算时间差，不超过1个月（30天）
  const timeDiff = endDate.getTime() - startDate.getTime();
  const daysDiff = Math.ceil(timeDiff / (1000 * 60 * 60 * 24));

  if (daysDiff > 30) {
    proxy.$modal.msgWarning(`第${rowIndex}行：时间跨度不能超过1个月（30天），当前为${daysDiff}天`);
  }
}

handleGetList();
getStudentList({ roleKey: "student" }).then((res) => {
  userList.value = res.data;
});
</script>

<style scoped>
.text-overflow {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  max-width: 200px;
}

.plan-table-container {
  width: 100%;
}

.plan-table-container .el-table {
  margin-bottom: 10px;
}
</style>
